#include "stdafx.h"
#include "ObjectManager.h"
#include "DebugObject.h"

DECLARE_SINGLETON_CPP(ObjectManager);

ObjectManager::ObjectManager(void)
{
	currentlyRemovingObjects = false;
}

ObjectManager::~ObjectManager(void)
{
}

void ObjectManager::UpdateObjects(float _dt)
{
	for (Objects3D::iterator i = m_Objects3D.begin(); i != m_Objects3D.end(); ++i)
	{
		(*i)->Update(_dt);
	}

	for (Objects2D::iterator i = m_Objects2D.begin(); i != m_Objects2D.end(); ++i)
	{
		(*i)->Update(_dt);
	}

	for(ObjectNPCs::iterator i = m_ObjectsNPCs.begin(); i != m_ObjectsNPCs.end(); ++i)
	{
		(*i)->Update(_dt);
	}
}

void ObjectManager::RenderObjects()
{
	for (Objects3D::iterator i = m_Objects3D.begin(); i != m_Objects3D.end(); ++i)
	{
		(*i)->Render();
	}

	for(ObjectNPCs::iterator i = m_ObjectsNPCs.begin(); i != m_ObjectsNPCs.end(); ++i)
	{
		(*i)->Render();
	}

	g_pD3DSprite->Begin(D3DXSPRITE_ALPHABLEND);

	for (Objects2D::iterator i = m_Objects2D.begin(); i != m_Objects2D.end(); ++i)
	{
		(*i)->Render();
	}

	g_pD3DSprite->End();

}

void ObjectManager::AddObject(BaseObjectBase* _object)
{
//#if _DEBUG
//	assert(_object != NULL);
//#else
//	if (_object == NULL)
//		return;
//#endif
	_object->AddRef();
	int nType = _object->m_eType;
	if(nType == BASEOBJECT)
	{
		m_Objects3D.push_back(_object);
	}
	else if(nType == BASEOBJECT2D)
	{
		m_Objects2D.push_back(_object);
	}
	else if(nType == OBJECTNPC)
	{
		m_ObjectsNPCs.push_back(_object);
	}
}


void ObjectManager::RemoveObject(BaseObjectBase* _object)
{
	int nType = _object->m_eType;

	if(nType == BASEOBJECT)
	{
		for (Objects3D::iterator i = m_Objects3D.begin(); i != m_Objects3D.end(); ++i)
		{
			if ((*i) == _object)
			{
				SAFE_RELEASE((*i));

				m_Objects3D.erase(i);
				return;
			}
		}
	}
	else if(nType == BASEOBJECT2D)
	{
		for (Objects2D::iterator i = m_Objects2D.begin(); i != m_Objects2D.end(); ++i)
		{
			if ((*i) == _object)
			{
				SAFE_RELEASE((*i));

				m_Objects2D.erase(i);
				return;
			}
		}
	}
	
	else if(nType == OBJECTNPC)
	{
		for(ObjectNPCs::iterator i = m_ObjectsNPCs.begin(); i != m_ObjectsNPCs.end(); ++i)
		{
			if ((*i) == _object)
			{
				SAFE_RELEASE((*i));

				m_ObjectsNPCs.erase(i);
				return;
			}
		}
	}
}

void ObjectManager::RemoveAllObjects(void)
{
	currentlyRemovingObjects = true;

	for (Objects3D::iterator i = m_Objects3D.begin(); i != m_Objects3D.end(); ++i)
	{
		SAFE_RELEASE((*i));
	}
	m_Objects3D.clear();

	for (Objects2D::iterator i = m_Objects2D.begin(); i != m_Objects2D.end(); ++i)
	{
		SAFE_RELEASE((*i));
	}
	m_Objects2D.clear();

	for(ObjectNPCs::iterator i = m_ObjectsNPCs.begin(); i != m_ObjectsNPCs.end(); ++i)
	{
		SAFE_RELEASE((*i));
	}
	m_ObjectsNPCs.clear();

	currentlyRemovingObjects = false;
}
